package com.frame.project.controller.system.role;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.frame.common.constant.UserConstants;
import com.frame.common.utils.page.MyPage;
import com.frame.common.utils.poi.ExcelUtil;
import com.frame.framework.aspectj.lang.annotation.Log;
import com.frame.framework.aspectj.lang.enums.BusinessType;
import com.frame.framework.web.controller.BaseController;
import com.frame.framework.web.error.WebError;
import com.frame.framework.web.page.TableDataInfo;
import com.frame.project.domain.system.role.Role;
import com.frame.project.domain.system.user.User;
import com.frame.project.domain.system.user.UserRole;
import com.frame.project.service.system.role.RoleService;
import com.frame.project.service.system.user.UserService;

/**
 * 
 * @className ：RoleController
 * @describe ：角色信息
 */
@Controller
@RequestMapping("/system/role")
public class RoleController extends BaseController
{
    private String prefix = "system/role";

    @Autowired
    private RoleService roleService;

    @Autowired
    private UserService userService;

    @RequiresPermissions("system:role:view")
    @GetMapping()
    public String role()
    {
        return prefix + "/role";
    }

    @RequiresPermissions("system:role:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Role role,@RequestParam(defaultValue = "0") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize)
    {
        startPage();
        MyPage<Role> findByPage = roleService.findByPage(role, pageNum, pageSize);
        return getDataTable(findByPage);
    }

    @Log(title = "角色管理", businessType = BusinessType.EXPORT)
    @RequiresPermissions("system:role:export")
    @PostMapping("/export")
    @ResponseBody
    public WebError export(Role role)
    {
    	MyPage<Role> page = roleService.findByPage(role, 0, Integer.MAX_VALUE);
        ExcelUtil<Role> util = new ExcelUtil<Role>(Role.class);
        return util.exportExcel(page.getContent(), "角色数据");
    }

    /**
     * 新增角色
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存角色
     */
    @RequiresPermissions("system:role:add")
    @Log(title = "角色管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public WebError addSave(@Validated Role role)
    {
        if (UserConstants.ROLE_NAME_NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role)))
        {
            return error(-1,"新增角色'" + role.getRoleName() + "'失败，角色名称已存在");
        }
        else if (UserConstants.ROLE_KEY_NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role)))
        {
            return error(-1,"新增角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        roleService.insertRole(role);
        return success();

    }

    /**
     * 修改角色
     */
    @GetMapping("/edit/{roleId}")
    public String edit(@PathVariable("roleId") Long roleId, Model model)
    {
    	roleService.checkRoleDataScope(roleId);
    	model.addAttribute("role", roleService.findById(roleId));
        return prefix + "/edit";
    }

    /**
     * 修改保存角色
     */
    @RequiresPermissions("system:role:edit")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public WebError editSave(@Validated Role role)
    {
        WebError web = roleService.checkRoleAllowed(role.getId());
        if(web.getCode() == -1) {
        	return web;
        }
        
        if (UserConstants.ROLE_NAME_NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role)))
        {
            return error(-1,"修改角色'" + role.getRoleName() + "'失败，角色名称已存在");
        }
        else if (UserConstants.ROLE_KEY_NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role)))
        {
            return error(-1,"修改角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        roleService.updateRole(role);
        return success();
    }

    /**
     * 角色分配数据权限
     */
    @GetMapping("/authDataScope/{roleId}")
    public String authDataScope(@PathVariable("roleId") Long roleId, Model model)
    {
    	model.addAttribute("role", roleService.findById(roleId));
        return prefix + "/dataScope";
    }

    /**
     * 保存角色分配数据权限
     */
    @RequiresPermissions("system:role:edit")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PostMapping("/authDataScope")
    @ResponseBody
    public WebError authDataScopeSave(Role role)
    {
    	WebError web = roleService.checkRoleAllowed(role.getId());
        if(web.getCode() == -1) {
        	return web;
        }
        roleService.authDataScope(role);
        setSysUser(userService.findById(getSysUser().getId()));
        
        return success();
    }

    @RequiresPermissions("system:role:remove")
    @Log(title = "角色管理", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public WebError remove(String ids)
    {
       return roleService.deleteRoleByIds(ids);
    }

    /**
     * 校验角色名称
     */
    @PostMapping("/checkRoleNameUnique")
    @ResponseBody
    public String checkRoleNameUnique(Role role)
    {
        return roleService.checkRoleNameUnique(role);
    }

    /**
     * 校验角色权限
     */
    @PostMapping("/checkRoleKeyUnique")
    @ResponseBody
    public String checkRoleKeyUnique(Role role)
    {
        return roleService.checkRoleKeyUnique(role);
    }

    /**
     * 选择菜单树
     */
    @GetMapping("/selectMenuTree")
    public String selectMenuTree()
    {
        return prefix + "/tree";
    }

    /**
     * 角色状态修改
     */
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @RequiresPermissions("system:role:edit")
    @PostMapping("/changeStatus")
    @ResponseBody
    public WebError changeStatus(Role role)
    {
    	WebError web = roleService.checkRoleAllowed(role.getId());
        if(web.getCode() == -1) {
        	return web;
        }
        roleService.changeStatus(role);
        return success();
    }

    /**
     * 分配用户
     */
    @RequiresPermissions("system:role:edit")
    @GetMapping("/authUser/{roleId}")
    public String authUser(@PathVariable("roleId") Long roleId, Model model)
    {
    	model.addAttribute("role", roleService.findById(roleId));
        return prefix + "/authUser";
    }

    /**
     * 查询已分配用户角色列表
     */
    @RequiresPermissions("system:role:list")
    @PostMapping("/authUser/allocatedList")
    @ResponseBody
    public TableDataInfo allocatedList(User user,@RequestParam(defaultValue = "0") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize)
    {
        startPage();
        MyPage<User> page = userService.selectAllocatedList(user, pageNum, pageSize);
        return getDataTable(page);
    }

    /**
     * 取消授权
     */
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @PostMapping("/authUser/cancel")
    @ResponseBody
    public WebError cancelAuthUser(UserRole userRole)
    {
    	roleService.deleteAuthUser(userRole);
        return success();
    }

    /**
     * 批量取消授权
     */
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @PostMapping("/authUser/cancelAll")
    @ResponseBody
    public WebError cancelAuthUserAll(Long roleId, String userIds)
    {
    	roleService.deleteAuthUsers(roleId, userIds);
        return success();
    }

    /**
     * 选择用户
     */
    @GetMapping("/authUser/selectUser/{roleId}")
    public String selectUser(@PathVariable("roleId") Long roleId, Model model)
    {
    	model.addAttribute("role", roleService.findById(roleId));
        return prefix + "/selectUser";
    }

    /**
     * 查询未分配用户角色列表
     */
    @RequiresPermissions("system:role:list")
    @PostMapping("/authUser/unallocatedList")
    @ResponseBody
    public TableDataInfo unallocatedList(User user,@RequestParam(defaultValue = "0") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize)
    {
        startPage();
        MyPage<User> page = userService.selectUnallocatedList(user, pageNum, pageSize);
        return getDataTable(page);
    }

    /**
     * 批量选择用户授权
     */
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @PostMapping("/authUser/selectAll")
    @ResponseBody
    public WebError selectAuthUserAll(Long roleId, String userIds)
    {
    	roleService.insertAuthUsers(roleId, userIds);
        return success();
    }
}